import router from 'koa-router';
import DBConnectTool from '../com/DBTool/DBConnectTool';
import ContentTypeTool from '../lib/ContentTypeTool';

const appFileRoutes = new router({prefix: '/appFile'});

appFileRoutes
    .get('/getFileByFullPath', async (ctx: any) => {
        let {DBName, fullPath} = ctx.request.query;
        if (DBName && fullPath) {
            let dbTool = await DBConnectTool.openDB(DBName);
            let file = await dbTool.getFileByFullPath(fullPath);

            if (!file || !file.file_data) {
                throw new Error('文件不存在，路径：' + fullPath);
            } else {
                let contentType = ContentTypeTool.getContentType(file.file_name);
                ctx.set('content-type', contentType);
                ctx.set('content-Disposition', `attachment;filename=${file.file_name}`);
                ctx.body = file.file_data;
            }
        } else {
            ctx.status = 404;
        }
    })
    .get('/getFileByMd5', async (ctx: any) => {
        let {DBName, md5} = ctx.request.query;
        if (DBName && md5) {
            let dbTool = await DBConnectTool.openDB(DBName);
            let file = await dbTool.getFileByMd5(md5);

            if (!file || !file.file_data) {
                throw new Error('文件不存在，MD5：' + md5);
            } else {
                let contentType = ContentTypeTool.getContentType(file.file_name);
                ctx.set('content-type', contentType);
                ctx.set('content-Disposition', `attachment;filename=${file.file_name}`);
                ctx.body = file.file_data;
            }
        } else {
            ctx.status = 404;
        }
    });


export default appFileRoutes;
